#include <session.h>

#include<queue>

Session::Session(QObject *parent = nullptr)
	: QObject(parent)
{
	init();
}

size_t Session::read(char* buffer, size_t maxLen) {
	size_t readBytes = socket_.read(buffer, maxLen);
	if (readBytes < 0) {
		qDebug() << "read error: " << socket_.errorString();
		socket_.close();
	}
	return readBytes;
}

bool Session::write(char* buffer, size_t len) {
	while (len>0) {
		qint64 bytesWrite = socket_.write(buffer, len);
		if (bytesWrite < 0) {
			qDebug() << socket_.errorString();
			return false;
		}
		buffer += bytesWrite;
		len -= bytesWrite;
	}
	return len == 0;
}

bool Session::write(std::shared_ptr<SendNode> sendNode) {
	if (!sendNode) {
		return false;
	}
	try {
		int bytesWrite = 0;
		//while (bytesWrite < MSG_HEADER_LEN) {
		//	bytesWrite += socket_.write(sendNode->data_ + bytesWrite, MSG_HEADER_LEN - bytesWrite);
		//}
		//bytesWrite = 0;
		// 只写入sendNode的data_成员
		while (bytesWrite < sendNode->totalLen_) {
			bytesWrite += socket_.write(sendNode->data_ + bytesWrite, sendNode->totalLen_ - bytesWrite);
		}
	}
	catch (const std::exception& error) {
		qDebug() << error.what();
		return false;
	}
	return true;
}


bool Session::isReadable() {
	return socket_.isReadable();
}


bool Session::isConnected() {
	return socket_.state() == QTcpSocket::ConnectedState;
}

void Session::init() {
	connect(&socket_, &QTcpSocket::stateChanged, [&](QTcpSocket::SocketState state) {
		QString info = state_ == QTcpSocket::ConnectedState ? "连接断开" : "连接失败";
		switch (state)
		{
		case QTcpSocket::SocketState::UnconnectedState:
			QMessageBox::critical(nullptr, "connect", info);
			state_ = state;
			break;
		case QTcpSocket::SocketState::ConnectingState:
			qDebug() << "connecting......";
			break;
		case QTcpSocket::SocketState::ConnectedState:
			QMessageBox::information(nullptr, "connect", "连接成功!");
			state_ = state;
			break;
		case QTcpSocket::SocketState::ClosingState:
		case QTcpSocket::SocketState::HostLookupState:
		case QTcpSocket::SocketState::BoundState:
		case QTcpSocket::SocketState::ListeningState:
		default:
			break;
		}
		});

	connect(&socket_, &QTcpSocket::readyRead, [&]() {
		emit this->readyRead();
		});

	//connect(&socket_, &QTcpSocket::disconnected, [=]() {

	//	});
	//connect(&socket_, &QTcpSocket::connected, [=]() {
	//	QString info = socket_.peerAddress().toString() + ":" + QString::asprintf("%1").arg(socket_.peerPort());
	//	QMessageBox::information(nullptr, "connect", info);
	//	});
}

QTcpSocket::SocketState Session::state() {
	return socket_.state();
}


bool Session::connectToHost(const QString& ip, uint16_t port) {
	socket_.connectToHost(ip, port);
	return true;
}

void Session::disconnectFromHost() {
	socket_.disconnectFromHost();
}


Session::~Session()
{}
